package com.drm.netschool.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.drm.common.util.ConfigUtil;
import com.drm.common.util.CookieUtil;
import com.drm.common.util.CreateRandom;
import com.drm.common.util.DateUtil;
import com.drm.common.util.EncryptTool;
import com.drm.common.util.RegexUtil;
import com.drm.common.util.StringUtil;
import com.drm.common.util.constants.Constants;
import com.drm.netschool.entity.DrmUser;
import com.drm.netschool.redis.RedisUtil;
import com.drm.netschool.service.DrmSystemSettingService;
import com.drm.netschool.service.DrmUserService;
import com.drm.netschool.service.mail.MailService;
import com.drm.netschool.web.form.FindPasswordForm;

/**
 * Created by CUIJB on 2015年7月25日
 */
@Controller
@RequestMapping("/member/")
public class FindPasswordController {

	private Logger LOGGER = LoggerFactory.getLogger(FindPasswordController.class);

	@Autowired
	private DrmUserService userService;
	
	@Autowired
	private MailService mailService;

	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private DrmSystemSettingService systemSettingService;
	
	@RequestMapping(value = "/find-password", method = RequestMethod.GET)
	public String findPassword(@ModelAttribute("form") FindPasswordForm form) {
		form.setMetaInfo(systemSettingService.getDrmSystemSetting());
		return "login/find-password";
	}

	@RequestMapping(value = "/find-password", method = RequestMethod.POST)
	public String doFindPassword(@ModelAttribute("form") FindPasswordForm form, HttpServletRequest request, HttpServletResponse response) {
		form.setMetaInfo(systemSettingService.getDrmSystemSetting());
		if (form == null || StringUtil.empty(form.getUserName()) || StringUtil.empty(form.getCheckCode())) {
			form.putError("find_password", "参数有误");
			return "login/find-password";
		}
		try {
			CookieUtil cookieUtil = new CookieUtil(request, response, ConfigUtil.getString("cookie.domain"));
			String key = cookieUtil.getCookie(Constants.COOKIE_USER_CHECKCODE);
			String sRand = redisUtil.getString(key);
			if (!sRand.equals(form.getCheckCode())) {
				form.putError("find_password", "校验码有误");
				return "login/find-password";
			}

			DrmUser user = userService.getByUserName(form.getUserName());
			if (user == null) {
				form.putError("find_password", "用户名未注册");
				return "login/find-password";
			}
		} catch (Exception e) {
			LOGGER.error(form.getUserName() + "系统异常", e);
			form.putError("find_password", "系统异常");
			return "login/find-password";
		}
		return "login/reset-password-mail";
	}

	@RequestMapping(value = "/reset-password-mail", method = RequestMethod.POST)
	public String doResetPasswordMail(@ModelAttribute("form") FindPasswordForm form) {
		form.setMetaInfo(systemSettingService.getDrmSystemSetting());
		if (form == null || StringUtil.empty(form.getEmail())) {
			form.putError("email", "参数有误");
			return "login/reset-password-mail";
		}

		if (!RegexUtil.isEmail(form.getEmail())) {
			form.putError("email", "邮箱格式有误");
			return "login/reset-password-mail";
		}
		DrmUser user = userService.getByUserNameAndEmail(form.getUserName(), form.getEmail());
		if (user == null) {
			form.putError("email", "邮箱验证失败");
			return "login/validate-mail-fail";
		}
		
		try {
			//发送激活邮件
	    	String token = EncryptTool.md5Hex(EncryptTool.sha1HEX(DateUtil.dateToStr(DateUtil.current(), DateUtil.FORMAT_DEFAULT_MIN)));
	     	String checkurl = Constants.DOMAIN + "/member/reset-password?token="+token+"&userId="+user.getUserId();
	     	String checkCode = CreateRandom.createRandom(false, 6);
	     	Map<String, Object> param = new HashMap<String, Object>();
	     	param.put("url", checkurl);
	     	param.put("userName", form.getUserName());
	     	param.put("checkCode", checkCode);
	     	param.put("domain", form.getDomain());
	     	mailService.sendMail("user-reset-password-mail", param, form.getEmail(), true);
	     	
	     	//缓存激活链接的token & userId
	     	redisUtil.setString(token, user.getUserId() + "", 60*60*2);
	     	//缓存校验码
	     	redisUtil.setString("reset_password_checkcode_" + user.getUserId(), checkCode, 60*60*2);
		} catch (Exception e) {
			LOGGER.error(form.getEmail() + "验证邮箱失败", e);
			form.putError("email", "邮箱验证失败");
			return "login/validate-mail-fail";
		}
		return "login/validate-mail-succ";
	}

	@RequestMapping(value = "/reset-password", method = RequestMethod.GET)
	public String resetPassword(@ModelAttribute("form") FindPasswordForm form) {
		form.setMetaInfo(systemSettingService.getDrmSystemSetting());
		return "login/reset-password";
	}
	
	@RequestMapping(value = "/reset-password", method = RequestMethod.POST)
	public String doResetPassword(@ModelAttribute("form") FindPasswordForm form) {
		form.setMetaInfo(systemSettingService.getDrmSystemSetting());
		if(form == null || StringUtil.empty(form.getCheckCode()) || form.getUserId() == null || form.getUserId() <= 0){
			form.putError("reset_password", "参数错误");
			return "login/validate-mail-fail";
		}
		
		if(!form.getNewPwd().equals(form.getConfirmPwd())){
			form.putError("reset_password", "密码和确认密码不一致");
			return "login/validate-mail-fail";
		}
		
		String userId = redisUtil.getString(form.getToken());
    	if(StringUtil.empty(userId)){
    		form.putError("reset_password", "链接已失效");
    		return "login/validate-mail-fail";
    	}
    	if(!userId.equals(form.getUserId()+"")){
    		form.putError("reset_password", "用户ID错误,请重新找回密码!");
    		return "login/validate-mail-fail";
    	}
    	
    	String checkCode = redisUtil.getString("reset_password_checkcode_" + userId);
    	if(StringUtil.empty(checkCode) || !checkCode.equals(form.getCheckCode().trim())){
    		form.putError("reset_password", "链接已失效");
    		return "login/validate-mail-fail";
    	}
		int result = userService.resetPassword(form.getUserId(), form.getNewPwd());
		if (result == 0) {
			form.putError("reset_password", "密码重置失败");
			return "login/validate-mail-fail";
		}
		form.putError("reset_password", "密码重置成功");
		return "login/login";
	}
}
